﻿Imports System.Data.SqlClient
Imports System.IO

Public Class frmClaimsUpdate

    Public SNo As Integer
    Public ClaimNo As String

    Sub FillClaimsNotes()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select * From ClaimsNotes Where ClaimNo=" & SNo & "Order By SNo", cnn)
            Dim Reader As SqlDataReader

            Me.txtProgressNotes.Clear()

            Dim ListHeader, ListNotes As New ArrayList

            cnn.Open()
            Reader = cmd.ExecuteReader
            While (Reader.Read)
                Me.txtProgressNotes.Text += Reader.Item("SavedUser") & "     " & Format(CDate(Reader.Item("SavedDate")), "yyyy/MM/dd hh:mm:ss tt") & _
                                        Chr(13) & Reader.Item("Notes") & Chr(13) & Chr(13)

                ListHeader.Add(Reader.Item("SavedUser") & "     " & Format(CDate(Reader.Item("SavedDate")), "yyyy/MM/dd hh:mm:ss tt"))
                ListNotes.Add(Reader.Item("Notes"))
            End While
            cnn.Close()

            For Each T As String In ListHeader
                txtProgressNotes.SelectionStart = txtProgressNotes.Find(T)
                Dim bfont As New Font(txtProgressNotes.Font, FontStyle.Bold)
                txtProgressNotes.SelectionFont = bfont
                txtProgressNotes.SelectionColor = Color.Blue
            Next

            Me.txtProgressNotes.ScrollToCaret()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillRejectionList()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select * From ClaimsRejectionReasons Order By RejectionReason", cnn)
            Dim Reader As SqlDataReader

            Me.CombRejectionReason.Items.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Me.CombRejectionReason.Items.Add(Reader.Item("RejectionReason"))
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillUsersList()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select FullName From Users Order By FullName", cnn)
            Dim Reader As SqlDataReader

            Me.ChListContacts.Items.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Me.ChListContacts.Items.Add(Reader.Item("FullName"))
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillCarsMake()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select * From CarsMake Order By CarsMake", cnn)
            Dim Reader As SqlDataReader

            Me.CombCarMake.Items.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Dim Item As New ListBox
                Me.CombCarMake.Items.Add(Reader.Item("CarsMake"))
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub frmClaimsUpdate_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        FillCarsMake()
        FillUsersList()

        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select SNo,ClaimNo,ClientID,CLientName,ClaimNo,Status,InsuranceCompany,PolicyNo,MembName,MedIDCarNo,ClaimAmount," & _
                                      "IsNull(CarsMake,N'') CarsMake,DateOfLoss,DateOfReceive,DateOfSubmission,DateOfDeadline,IsNull(InsurCompClaimNo,N'') InsurCompClaimNo," & _
                                      "IsNull(Notes,N'') Notes,SavedUser,SavedDate From Claims Where SNo=" & SNo, cnn)
            Dim Reader As SqlDataReader
            Dim Status As String

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Me.txtClientID.Text = Reader.Item("ClientID")
                Me.txtClientName.Text = Reader.Item("ClientName")
                Me.txtClaimNo.Text = Reader.Item("ClaimNo")
                Me.txtInsuranceCompany.Text = Reader.Item("InsuranceCompany")
                Me.txtPolicyNo.Text = Reader.Item("PolicyNo")
                Me.txtMemberName.Text = Reader.Item("MembName")
                Me.txtMedIDPlateNo.Text = Reader.Item("MedIDCarNo")
                Me.CombCarMake.Text = Reader.Item("CarsMake")
                Me.txtInsurCompClaimNo.Text = Reader.Item("InsurCompClaimNo")
                Me.txtClaimAmount.Text = CDbl(Reader.Item("ClaimAmount")).ToString("N2")
                Me.DTPDateOfLoss.Text = CDate(Reader.Item("DateOfLoss"))
                Me.DTPDateOfReceive.Text = CDate(Reader.Item("DateOfReceive"))
                Me.DTPDateOfSubmission.Text = CDate(Reader.Item("DateOfSubmission"))
                Me.DTPDateOfDeadline.Text = CDate(Reader.Item("DateOfDeadline"))
                Me.txtClaimNotes.Text = Reader.Item("Notes")

                Status = Reader.Item("Status")
                Me.txtStatus.Text = Reader.Item("Status")
            End While
            cnn.Close()

            FillClaimsNotes()
            FillClaimsPayments()
            FillClaimsRejectedPayments()
            FillClaimsDocuments()
            FillRejectionList()

            'Check status
            If Status = "Active" Then
                Me.txtStatus.BackColor = Color.Yellow
                Me.RActive.Checked = True

            ElseIf Status = "Closed" Then
                Me.txtStatus.BackColor = Color.Magenta
                Me.RClosed.Checked = True

            ElseIf Status = "Settled" Then
                Me.txtStatus.BackColor = Color.GreenYellow
                Me.RSettled.Checked = True

            ElseIf Status = "Rejected" Then
                Me.txtStatus.BackColor = Color.Red
                Me.RRejected.Checked = True

            ElseIf Status = "Pending" Then
                Me.txtStatus.BackColor = Color.Orange
                Me.RPending.Checked = True

            ElseIf Status = "Special Approval" Then
                Me.txtStatus.BackColor = Color.LightSteelBlue
                Me.RSpecialApproval.Checked = True
            End If

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillClaimsPayments()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select * From ClaimsPayments Where ClaimNo=" & SNo, cnn)
            Dim Reader As SqlDataReader

            Me.GridPayments.Rows.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While (Reader.Read)
                Me.GridPayments.Rows.Add(New String() {Reader.Item("SNo"), CDbl(Reader.Item("Amount")).ToString("N2"), Reader.Item("PaymentDetails"), _
                                                       Reader.Item("SavedUser"), Format(CDate(Reader.Item("SavedDate")), "yyyy/MM/dd"), "Delete"})
            End While
            cnn.Close()

            CalculateClaimAmounts()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillClaimsRejectedPayments()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select * From ClaimsRejections Where ClaimNo=" & SNo, cnn)
            Dim Reader As SqlDataReader

            Me.GridRejectedPayments.Rows.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While (Reader.Read)
                Me.GridRejectedPayments.Rows.Add(New String() {Reader.Item("SNo"), CDbl(Reader.Item("Amount")).ToString("N2"), Reader.Item("RejectionReason"), _
                                                       Reader.Item("SavedUser"), Format(CDate(Reader.Item("SavedDate")), "yyyy/MM/dd"), "Delete"})
            End While
            cnn.Close()

            CalculateClaimAmounts()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillClaimsDocuments()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim Dir As New IO.DirectoryInfo(FTPAddress + "Claims\" + ClaimNo)
            Dim DirFiles As IO.FileInfo() = Dir.GetFiles()

            Me.GridFiles.Rows.Clear()

            'list the names of all files in the specified directory
            For Each Fi As FileInfo In DirFiles
                Me.GridFiles.Rows.Add(New String() {Fi.Name, Fi.CreationTime.ToString("yyyy/MM/dd hh:mm tt"), "Open", "Delete"})
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString)
        End Try
    End Sub

    Function ValidatePaymentsAmount() As Boolean
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim ClaimAmount, PaidAmount, RejectedAmount As Boolean

            For Each row As DataGridViewRow In Me.GridPayments.Rows
                ClaimAmount += CDbl(row.Cells(2).Value)
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Function

    Sub CalculateClaimAmounts()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim ClaimAmount, Paid, Rejected, UP As Double

            ClaimAmount = CDbl(Me.txtClaimAmount.Text)

            For Each row As DataGridViewRow In Me.GridPayments.Rows
                Paid += CDbl(row.Cells(1).Value)
            Next

            For Each row As DataGridViewRow In Me.GridRejectedPayments.Rows
                Rejected += CDbl(row.Cells(1).Value)
            Next

            Me.txtPaid.Text = Paid.ToString("N2")
            Me.txtRejected.Text = Rejected.ToString("N2")
            Me.txtUnderProcessing.Text = CDbl(CDbl(Me.txtClaimAmount.Text) - Paid - Rejected).ToString("N2")

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub txtPaidAmount_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPaidAmount.Validated
        Me.txtPaidAmount.Text = CDbl(Me.txtPaidAmount.Text).ToString("N2")
    End Sub

    Private Sub txtPaidAmount_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtPaidAmount.Validating
        If Me.txtPaidAmount.Text.Trim.Length = 0 Then
            Me.txtPaidAmount.Text = 0
        End If

        Dim currency As Decimal
        'Convert the current value to currency, with or without a currency symbol.
        If Not Decimal.TryParse(Me.txtPaidAmount.Text, Globalization.NumberStyles.Number, Nothing, currency) Then
            'Don't let the user leave the field if the value is invalid.
            With Me.txtPaidAmount
                .HideSelection = False
                .SelectAll()
                MessageBox.Show("Please enter a valid amount.", _
                                "Invalid Value", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Error)
                .HideSelection = True
            End With
            e.Cancel = True
        End If
    End Sub

    Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridFiles.CellClick
        If e.ColumnIndex = 2 Then
            'Dim Fi As New FileInfo(FTPAddress + "Claims\" + ClaimNo + "\" + Me.GridFiles.Rows(e.RowIndex).Cells(0).Value)
            'Fi.Open(FileMode.Open, FileAccess.ReadWrite)
            Try
                Me.Cursor = Cursors.WaitCursor

                Dim FilePath As String = FTPAddress + "Claims\" + ClaimNo + "\" + Me.GridFiles.Rows(e.RowIndex).Cells(0).Value
                System.Diagnostics.Process.Start(FilePath)

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try

        ElseIf e.ColumnIndex = 3 Then
            If MsgBox("Confirm delete?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                Try
                    Me.Cursor = Cursors.Default

                    Dim Fi As New FileInfo(FTPAddress + "Claims\" + ClaimNo + "\" + Me.GridFiles.Rows(e.RowIndex).Cells(0).Value)

                    Fi.Delete()

                    FillClaimsDocuments()

                    Me.Cursor = Cursors.Default
                Catch ex As Exception
                    Me.Cursor = Cursors.Default
                    If cnn.State = ConnectionState.Open Then
                        cnn.Close()
                    End If
                    MsgBox(ex.ToString)
                End Try
            End If
        End If
    End Sub

    Sub ShowFile(ByVal SNo As Integer)
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd1 As New SqlCommand("Select DocName,Doc From ClaimsDocuments Where SNo=" & SNo, cnn)
            Dim Reader As SqlDataReader

            Dim FileName As String
            Dim FileByte As Byte()

            cnn.Open()
            Reader = cmd1.ExecuteReader
            While Reader.Read
                FileName = "D:\" & Reader.Item(0)

                If File.Exists(FileName) Then
                    File.Delete(FileName)
                End If

                Dim fs As New FileStream(FileName, FileMode.Create, FileAccess.Write)
                FileByte = CType(Reader.Item(1), Byte())

                fs.Write(FileByte, 0, FileByte.Length)
                fs.Close()

                System.Diagnostics.Process.Start(FileName)
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub SaveNotes()
        If Me.txtNotes.Text.Trim.Length = 0 Then
            Me.txtNotes.Clear()
            Me.txtNotes.Focus()
            Exit Sub
        Else
            Try
                Me.Cursor = Cursors.WaitCursor
                Dim cmd As New SqlCommand("Insert Into ClaimsNotes (ClaimNo,Notes,SavedUser) Values " & _
                                          "(@ClaimNo,@Notes,@SavedUser)", cnn)
                cnn.Open()

                'Add values
                cmd.Parameters.AddWithValue("@ClaimNo", SNo)
                cmd.Parameters.AddWithValue("@Notes", Me.txtNotes.Text.Trim)
                cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)

                cmd.ExecuteNonQuery()
                cnn.Close()

                'Send notification
                Dim Subject, Body As String
                Dim Receivers As New ArrayList

                If Me.ChListContacts.CheckedItems.Count > 0 Then
                    Subject = "Oasis - IBS Notification - Claims Management System"
                    Body = "Your received a notification from: <B>" & CurrentUser & _
                           "</B>, regarding claim # <B>" & ClaimNo & "</B><br/><br/>" & _
                           "Please don't reply to this email.<br/>" & _
                           "Sent from Oasis - Insurance Broker System"
                    For i As Integer = 0 To Me.ChListContacts.Items.Count - 1
                        If Me.ChListContacts.GetItemChecked(i) Then
                            Receivers.Add(GetUserEmail(Me.ChListContacts.Items(i)))
                        End If
                    Next

                    SendEmail(Subject, Body, Receivers)

                    MsgBox("Notification has been sent successfully")
                End If

                FillClaimsNotes()

                Me.txtNotes.Clear()
                Me.txtNotes.Focus()
                For i As Integer = 0 To Me.ChListContacts.Items.Count - 1
                    Me.ChListContacts.SetItemChecked(i, False)
                Next

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtNotes.KeyDown
        If e.Shift And e.KeyCode = Keys.Enter Then
            Exit Sub
        ElseIf e.KeyCode = Keys.Enter Then
            SaveNotes()
        End If
    End Sub

    Sub UpdateStatus()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand
            Dim Trans As SqlTransaction

            cnn.Open()
            Trans = cnn.BeginTransaction
            cmd.Connection = cnn
            cmd.Transaction = Trans

            cmd.CommandText = "update Claims set Status=@Status Where SNo=" & SNo

            'Add values

            If RActive.Checked = True Then
                cmd.Parameters.AddWithValue("@Status", "Active")

            ElseIf RClosed.Checked = True Then
                cmd.Parameters.AddWithValue("@Status", "Closed")

            ElseIf RSettled.Checked = True Then
                cmd.Parameters.AddWithValue("@Status", "Settled")

            ElseIf RRejected.Checked = True Then
                cmd.Parameters.AddWithValue("@Status", "Rejected")

            ElseIf RPending.Checked = True Then
                cmd.Parameters.AddWithValue("@Status", "Pending")

            ElseIf RSpecialApproval.Checked = True Then
                cmd.Parameters.AddWithValue("@Status", "Special Approval")
            End If

            cmd.ExecuteNonQuery()

            Trans.Commit()
            cnn.Close()

            If RActive.Checked = True Then
                Me.txtStatus.BackColor = Color.Yellow
                Me.txtStatus.Text = "Active"

            ElseIf RClosed.Checked = True Then
                Me.txtStatus.BackColor = Color.Magenta
                Me.txtStatus.Text = "Closed"

            ElseIf RSettled.Checked = True Then
                Me.txtStatus.BackColor = Color.GreenYellow
                Me.txtStatus.Text = "Settled"

            ElseIf RRejected.Checked = True Then
                Me.txtStatus.BackColor = Color.Red
                Me.txtStatus.Text = "Rejected"

            ElseIf RPending.Checked = True Then
                Me.txtStatus.BackColor = Color.Orange
                Me.txtStatus.Text = "Pending"

            ElseIf RSpecialApproval.Checked = True Then
                Me.txtStatus.BackColor = Color.LightSteelBlue
                Me.txtStatus.Text = "Special Approval"
            End If

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub txtRejectionAmount_Validated(sender As System.Object, e As System.EventArgs) Handles txtRejectionAmount.Validated
        Me.txtRejectionAmount.Text = CDbl(Me.txtRejectionAmount.Text).ToString("N2")
    End Sub

    Private Sub txtRejectionAmount_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtRejectionAmount.Validating
        If Me.txtRejectionAmount.Text.Trim.Length = 0 Then
            Me.txtRejectionAmount.Text = 0
        End If

        Dim currency As Decimal
        'Convert the current value to currency, with or without a currency symbol.
        If Not Decimal.TryParse(Me.txtRejectionAmount.Text, Globalization.NumberStyles.Number, Nothing, currency) Then
            'Don't let the user leave the field if the value is invalid.
            With Me.txtRejectionAmount
                .HideSelection = False
                .SelectAll()
                MessageBox.Show("Please enter a valid amount.", _
                                "Invalid Value", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Error)
                .HideSelection = True
            End With
            e.Cancel = True
        End If
    End Sub

    Private Sub RActive_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RActive.CheckedChanged
        UpdateStatus()
    End Sub

    Private Sub RSettled_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RSettled.CheckedChanged
        UpdateStatus()
    End Sub

    Private Sub RRejected_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RRejected.CheckedChanged
        UpdateStatus()
    End Sub

    Private Sub RPending_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RPending.CheckedChanged
        UpdateStatus()
    End Sub

    Private Sub RSpecialApproval_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RSpecialApproval.CheckedChanged
        UpdateStatus()
    End Sub

    Private Sub GridPayments_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridPayments.CellClick
        If e.RowIndex > -1 Then
            If e.ColumnIndex = 5 Then
                If MsgBox("Confirm delete?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    Try
                        Me.Cursor = Cursors.Default

                        Dim cmd As New SqlCommand
                        Dim Trans As SqlTransaction

                        cnn.Open()
                        Trans = cnn.BeginTransaction
                        cmd.Connection = cnn
                        cmd.Transaction = Trans

                        cmd.CommandText = "Delete From ClaimsPayments Where SNo=" & Me.GridPayments.Rows(e.RowIndex).Cells(0).Value
                        cmd.ExecuteNonQuery()

                        cmd.CommandText = "Delete From ClientsAcc Where ClaimRef=" & Me.GridPayments.Rows(e.RowIndex).Cells(0).Value
                        cmd.ExecuteNonQuery()

                        Trans.Commit()
                        cnn.Close()

                        MsgBox("Deleted Successfully!")

                        FillClaimsPayments()

                        Me.Cursor = Cursors.Default
                    Catch ex As Exception
                        Me.Cursor = Cursors.Default
                        If cnn.State = ConnectionState.Open Then
                            cnn.Close()
                        End If
                        MsgBox(ex.ToString)
                    End Try
                End If
            End If
        End If
    End Sub

    Private Sub GridRejectedPayments_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridRejectedPayments.CellClick
        If e.RowIndex > -1 Then
            If e.ColumnIndex = 5 Then
                If MsgBox("Confirm delete?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    Try
                        Me.Cursor = Cursors.Default

                        Dim cmd As New SqlCommand("Delete From ClaimsRejections Where SNo=" & Me.GridRejectedPayments.Rows(e.RowIndex).Cells(0).Value, cnn)

                        cnn.Open()
                        cmd.ExecuteNonQuery()
                        cnn.Close()

                        MsgBox("Deleted Successfully!")

                        FillClaimsRejectedPayments()

                        Me.Cursor = Cursors.Default
                    Catch ex As Exception
                        Me.Cursor = Cursors.Default
                        If cnn.State = ConnectionState.Open Then
                            cnn.Close()
                        End If
                        MsgBox(ex.ToString)
                    End Try
                End If
            End If
        End If
    End Sub

    Private Sub txtClaimAmount_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtClaimAmount.TextChanged
        CalculateClaimAmounts()
    End Sub

    Private Sub RClose_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RClosed.CheckedChanged
        UpdateStatus()
    End Sub

    Private Sub Button4_Click_1(sender As System.Object, e As System.EventArgs) Handles Button4.Click
        If CDbl(Me.txtPaidAmount.Text.Trim) = 0 OrElse Me.txtPaidAmount.Text.Trim.Length = 0 OrElse Me.txtPaymentDetails.Text.Trim.Length = 0 Then
            MsgBox("Please enter paid amount and payment details")
        ElseIf CDbl(Me.txtPaidAmount.Text) > CDbl(Me.txtUnderProcessing.Text) Then
            MsgBox("Please review the amount (underprocessing)")
            Me.txtPaidAmount.SelectAll()
            Me.txtPaidAmount.Focus()
        Else
            Try
                Me.Cursor = Cursors.WaitCursor

                Dim ClaimRef As Integer
                Dim cmd As New SqlCommand()
                Dim Trans As SqlTransaction
                Dim InsurCompanyAccNo As String = GetInsurCompPolAccNo(Me.txtInsuranceCompany.Text, Me.txtPolicyNo.Text)

                cnn.Open()
                Trans = cnn.BeginTransaction
                cmd.Connection = cnn
                cmd.Transaction = Trans

                cmd.CommandText = "Insert Into ClaimsPayments (ClaimNo,ClientNo,Amount,PaymentDetails,SavedUser) Values " & _
                                          "(@ClaimNo,@ClientNo,@Amount,@PaymentDetails,@SavedUser) Select SCOPE_IDENTITY()"

                'Add values
                cmd.Parameters.AddWithValue("@ClaimNo", SNo)
                cmd.Parameters.AddWithValue("@ClientNo", Me.txtClientID.Text.Trim)
                cmd.Parameters.AddWithValue("@Amount", CDbl(Me.txtPaidAmount.Text))
                cmd.Parameters.AddWithValue("@PaymentDetails", Me.txtPaymentDetails.Text.Trim)
                cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                ClaimRef = CInt(cmd.ExecuteScalar)


                If Me.RCreditNote.Checked = True Then
                    'Insert Credit
                    cmd.CommandText = "Insert Into ClientsAcc (ClaimRef,ClientID,ClientName,PolicyNo,InsurCompany,InsurCompanyAccNo," & _
                                      "PaymentDetails,TotalIn,SavedUser) " & _
                                      "Values (@ClaimRef,@ClientID,@ClientName,@PolicyNo,@InsurCompany,@InsurCompanyAccNo," & _
                                      "@PaymentDetails,@TotalIn,@SavedUser)"

                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@ClaimRef", ClaimRef)
                    cmd.Parameters.AddWithValue("@ClientID", Me.txtClientID.Text.Trim)
                    cmd.Parameters.AddWithValue("@ClientName", Me.txtClientName.Text.Trim)
                    cmd.Parameters.AddWithValue("@PolicyNo", Me.txtPolicyNo.Text.Trim)
                    cmd.Parameters.AddWithValue("@InsurCompany", Me.txtInsuranceCompany.Text)
                    cmd.Parameters.AddWithValue("@InsurCompanyAccNo", InsurCompanyAccNo)
                    cmd.Parameters.AddWithValue("@PaymentDetails", Me.txtPaymentDetails.Text)
                    cmd.Parameters.AddWithValue("@TotalIn", CDbl(Me.txtPaidAmount.Text.Trim))
                    cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                    cmd.ExecuteNonQuery()
                Else
                    'Insert Debit/Credit
                    cmd.CommandText = "Insert Into ClientsAcc (ClaimRef,ClientID,ClientName,PolicyNo,InsurCompany," & _
                                      "InsurCompanyAccNo,PaymentDetails,TotalIn,TotalOut,SavedUser) " & _
                                      "Values (@ClaimRef,@ClientID,@ClientName,@PolicyNo,@InsurCompany,@InsurCompanyAccNo," & _
                                      "@PaymentDetails,@TotalIn,@TotalOut,@SavedUser)"

                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@ClaimRef", ClaimRef)
                    cmd.Parameters.AddWithValue("@ClientID", Me.txtClientID.Text.Trim)
                    cmd.Parameters.AddWithValue("@ClientName", Me.txtClientName.Text.Trim)
                    cmd.Parameters.AddWithValue("@PolicyNo", Me.txtPolicyNo.Text.Trim)
                    cmd.Parameters.AddWithValue("@InsurCompany", Me.txtInsuranceCompany.Text)
                    cmd.Parameters.AddWithValue("@InsurCompanyAccNo", InsurCompanyAccNo)
                    cmd.Parameters.AddWithValue("@PaymentDetails", Me.txtPaymentDetails.Text)
                    cmd.Parameters.AddWithValue("@TotalIn", CDbl(Me.txtPaidAmount.Text.Trim))
                    cmd.Parameters.AddWithValue("@TotalOut", CDbl(Me.txtPaidAmount.Text.Trim))
                    cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                    cmd.ExecuteNonQuery()
                End If

                Trans.Commit()
                cnn.Close()

                MsgBox("Saved Successfully")

                FillClaimsPayments()

                Me.txtPaidAmount.Text = "0.00"
                Me.txtPaymentDetails.Clear()
                Me.txtPaidAmount.Focus()

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If CDbl(Me.txtRejectionAmount.Text.Trim) = 0 OrElse Me.txtRejectionAmount.Text.Trim.Length = 0 OrElse Me.CombRejectionReason.SelectedIndex = -1 Then
            MsgBox("Please enter rejected amount and select rejection reason")
        ElseIf CDbl(Me.txtRejectionAmount.Text) > CDbl(Me.txtUnderProcessing.Text) Then
            MsgBox("Please review the amount (underprocessing)")
            Me.txtRejectionAmount.SelectAll()
            Me.txtRejectionAmount.Focus()
        Else
            Try
                Me.Cursor = Cursors.WaitCursor
                Dim cmd As New SqlCommand("Insert Into ClaimsRejections (ClaimNo,ClientNo,Amount,RejectionReason,SavedUser) Values " & _
                                          "(@ClaimNo,@ClientNo,@Amount,@RejectionReason,@SavedUser)", cnn)
                cnn.Open()

                'Add values
                cmd.Parameters.AddWithValue("@ClaimNo", SNo)
                cmd.Parameters.AddWithValue("@ClientNo", Me.txtClientID.Text.Trim)
                cmd.Parameters.AddWithValue("@Amount", CDbl(Me.txtRejectionAmount.Text))
                cmd.Parameters.AddWithValue("@RejectionReason", Me.CombRejectionReason.SelectedItem)
                cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)

                cmd.ExecuteNonQuery()
                cnn.Close()

                MsgBox("Saved Successfully")

                FillClaimsRejectedPayments()

                Me.txtRejectionAmount.Text = "0.00"
                Me.CombRejectionReason.SelectedIndex = -1
                Me.txtRejectionAmount.Focus()

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand()
            Dim Trans As SqlTransaction

            cnn.Open()
            Trans = cnn.BeginTransaction
            cmd.Connection = cnn
            cmd.Transaction = Trans

            cmd.CommandText = "Update Claims Set MembName=@MembName,MedIDCarNo=@MedIDCarNo,InsurCompClaimNo=@InsurCompClaimNo," & _
                              "CarsMake=@CarsMake,ClaimAmount=@ClaimAmount,DateOfLoss=@DateOfLoss,DateOfReceive=@DateOfReceive," & _
                              "DateOfSubmission=@DateOfSubmission,DateOfDeadline=@DateOfDeadline,Notes=@Notes Where SNo=" & SNo

            'Add values
            cmd.Parameters.AddWithValue("@MembName", Me.txtMemberName.Text.Trim)
            cmd.Parameters.AddWithValue("@MedIDCarNo", Me.txtMedIDPlateNo.Text.Trim)
            cmd.Parameters.AddWithValue("@InsurCompClaimNo", Me.txtInsurCompClaimNo.Text.Trim)
            cmd.Parameters.AddWithValue("@CarsMake", Me.CombCarMake.Text.Trim)
            cmd.Parameters.AddWithValue("@ClaimAmount", CDbl(Me.txtClaimAmount.Text))
            cmd.Parameters.AddWithValue("@DateOfLoss", Me.DTPDateOfLoss.Value.ToShortDateString & " 10:10:10 AM")
            cmd.Parameters.AddWithValue("@DateOfReceive", Me.DTPDateOfReceive.Value.ToShortDateString & " 10:10:10 AM")
            cmd.Parameters.AddWithValue("@DateOfSubmission", Me.DTPDateOfSubmission.Value.ToShortDateString & " 10:10:10 AM")
            cmd.Parameters.AddWithValue("@DateOfDeadline", Me.DTPDateOfDeadline.Value.ToShortDateString & " 10:10:10 AM")
            cmd.Parameters.AddWithValue("@Notes", Me.txtClaimNotes.Text.Trim)
            cmd.ExecuteNonQuery()

            Trans.Commit()
            cnn.Close()

            MsgBox("Updated Successfully")

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        SaveNotes()
    End Sub

    Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
        Try
            Me.OpenFileDialog1.Filter = "All files (*.*)|*.*"
            If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

                'Set files
                Dim SelFile As FileInfo
                Dim SelFilePath, DestFilePath As String

                SelFilePath = Me.OpenFileDialog1.FileName
                SelFile = New FileInfo(SelFilePath)
                DestFilePath = FTPAddress + "Claims\" + ClaimNo + "\" + SelFile.Name

                My.Computer.Network.UploadFile(SelFilePath, DestFilePath, FTPUserName, FTPPassword, True, 500)

                FillClaimsDocuments()
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub
End Class